---
-- @classmod abtesting.adapter.runtime
-- @release 0.0.1
local modulename = "abtestingAdapterRuntime"

local _M = {}
local metatable = {__index = _M}

_M._VERSION = "0.0.1"

local log	    = require('abtesting.utils.log')
local cjson	    = require('cjson.safe')
local ERRORINFO = require('abtesting.error.errcode').info

---
-- @field fields
-- @warning this is a conf, may other file later
local fields= {}
fields.divModulename = 'divModulename'
fields.divDataKey = 'divDataKey'
fields.userInfoModulename = 'userInfoModulename'
local separator = ':'

---
-- runtimeInfoIO new function
-- @param database  opened redis
-- @param baseLibrary a library(prefix of redis key) of runtime info
-- @return runtimeInfoIO object
_M.new = function(self, database, baseLibrary)
	if not database then
		error{ERRORINFO.PARAMETER_NONE, 'need a object of redis'}
	end if not baseLibrary then
	    error{ERRORINFO.PARAMETER_NONE, 'need a library of runtime info'}
    end

    self.database     = database
    self.baseLibrary  = baseLibrary

    return setmetatable(self, metatable)
end

---
-- get runtime info(diversion modulename and diversion metadata key)
-- @param domain is a domain name to search runtime info
-- @return a table of diversion modulename and diversion metadata key
_M.get = function(self, domain)
    local database = self.database
    local divModulenameKey      = table.concat({self.baseLibrary, domain, fields.divModulename}, separator)
    local divDataKeyOfKey       = table.concat({self.baseLibrary, domain, fields.divDataKey}, separator)
    local userInfoModulenameKey = table.concat({self.baseLibrary, domain, fields.userInfoModulename}, separator)

    --log:debug('redis key: '.. divModulenameKey)
    --log:debug('redis key: '.. divDataKeyOfKey)
    --log:debug('redis key: '.. userInfoModulenameKey)

    local response, err = database:mget(divModulenameKey, divDataKeyOfKey, userInfoModulenameKey)
    if not response then
        error{ERRORINFO.REDIS_ERROR, err}
    end

    log:debug('redis => : ' .. cjson.encode(response))

    local runtimeInfo = {}
    runtimeInfo[fields.divModulename]      = response[1]
    runtimeInfo[fields.divDataKey]         = response[2]
    runtimeInfo[fields.userInfoModulename] = response[3]
    
    return runtimeInfo
end

return _M
